# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import os
import pymongo
import pymysql
import requests


class TianmaoguojiPipeline_img(object):
    def process_item(self, item, spider):
    #     os.makedirs('天猫国际', exist_ok=True)
    #     name = item['name'].replace('/', '').replace('*', '')
    #     img = requests.get(item['img_src'])
    #     with open('天猫国际/' + name + '.jpg', 'wb+') as f:
    #         f.write(img.content)
        return item


class TianmaoguojiPipeline_mongo(object):
    # def __init__(self):
    #     myclient = pymongo.MongoClient('127.0.0.1', 27017)
    #     if '天猫国际' in myclient.list_database_names():
    #         myclient.drop_database('天猫国际')
    #     mydb = myclient['天猫国际']
    #     self.mycol = mydb['商品列表']
    #     self._id = 1

    def process_item(self, item, spider):
        # item['_id'] = self._id
        # self.mycol.insert_one(dict(item))
        # self._id += 1
        return item


class TianmaoguojiPipeline_mysql(object):
    def __init__(self):
        self.db = pymysql.Connect(
            host='127.0.0.1',
            user='root',
            password='1111',
            port=3306,
            db='day14',
            charset='utf8'
        )
        self.cur = self.db.cursor()

    def process_item(self, item, spider):
        sql = "insert guoji values(0,'%s','%s','%s','%s','%s','%s','%s','%s','%s')" % (
            item['name'], item['miaoshu'], item['miaosu'], item['xianjia'], item['yuanjia'], item['guojia'],
            item['yishou'], item['shangpinid'], item['img_src'])
        self.cur.execute(sql)
        self.db.commit()
        return item

    # def close_spider(self, item, spider):
    #     self.cur.close()
    #     self.db.close()
